package com.dingding.service.usermangerservice.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.bean.databean.request.ReqDriverAuth;
import com.dingding.bean.databean.request.ReqReDriverAuth;
import com.dingding.bean.databean.response.DataResponse;
import com.dingding.bean.databean.response.ResDriverAuth;
import com.dingding.bean.databean.response.ResReDriverAuth;
import com.dingding.bean.entity.UserLogin;
import com.dingding.bean.entity.Vehicleinfo;
import com.dingding.common.core.config.SystemCode;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.service.BaseService;
import com.dingding.service.usermangerservice.IVehicleinfoService;
import com.dingding.upload.ImageUpload;

/**
 * 
 * @ClassName: VehicleinfoServiceImpl
 * @Description:车辆信息service实现
 * @author cheshaowei
 * @date 2015-10-21 上午10:37:46
 */
public class VehicleinfoServiceImpl extends BaseService implements IVehicleinfoService {

	private static final Logger log = Logger.getLogger(VehicleinfoServiceImpl.class);

	/**
	 * 
	 * @Title: driverAuth @Description:认证车主 @param driverAuth
	 *         认证车主数据请求封装bean @param dataResponse 数据响应bean @author
	 *         cheshaowei @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void driverAuth(ReqDriverAuth driverAuth, DataResponse dataResponse) {

		// 验证认证车主时客户端传入参数是否为空
		boolean isTrue = isPropertiesTrue(driverAuth);

		if (!isTrue) { // 存在空值
			log.error("车主认证请求参数为空:" + driverAuth.toString());
			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}

		// 判断车牌是否已经注册过,如果uvId不为空说明当前车牌已经注册过（同一车牌不能多次注册）
		if (ToolUtil.isNotBlank(driverAuth.getLisencePlate())) {

			String uvId = super.vehicleinfoDao.getUvId(driverAuth.getLisencePlate(), driverAuth.getDriverId());

			if (ToolUtil.isNotBlank(uvId)) {
				// 车牌号已被注册
				setStatus(dataResponse, SystemCode.LISENCEPLATE_EXITS_ERROR);
				return;
			}
		}

		// 根据用户ID获取车辆信息
		Vehicleinfo vehicleinfo = super.vehicleinfoDao.getVehicleinfo(driverAuth.getDriverId());

		if (vehicleinfo == null) {
			log.error("车主认证时获取车辆信息失败，用户ID是：" + driverAuth.getDriverId());
			setStatus(dataResponse, SystemCode.ERROR);
			return;
		}

		/**
		 * 修改人：冯硕楠 修改原因：添加出租车业务需求，认证车主时添加是否为出租 修改时间：2016年6月30日13:28:04 修改版本：V2.3
		 */
		if (driverAuth.getPublishType() == null) {
			log.error("车主认证请求参数为空：" + driverAuth.toString());
			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}
		// 添加是否为出租车
		vehicleinfo.setRegistrationType(driverAuth.getPublishType());
		// 上传图片及数据设置
		List<String> listImageAddress = dataAdd(driverAuth, vehicleinfo);

		if (listImageAddress == null) {
			setStatus(dataResponse, SystemCode.UPLOAD_ERROR);
			return;
		}

		// 设置响应bean的三个图片的地址
		ResDriverAuth resDriverAuth = new ResDriverAuth();
		// 新的审核状态
		resDriverAuth.setVstatus(1);
		// 行驶证
		resDriverAuth.setXszImage(listImageAddress.get(0));
		// 驾驶证
		resDriverAuth.setJszImage(listImageAddress.get(1));
		// 车辆图片
		resDriverAuth.setVehicleImage(listImageAddress.get(2));

		setStatus(dataResponse, SystemCode.SUCCESS);
		dataResponse.setResponseBody(resDriverAuth);
	}

	/**
	 * 
	 * @Title: dataAdd @Description:图片上传数据及设置保存数据 @return true:成功
	 *         false:失败 @author cheshaowei @throws
	 */
	private List<String> dataAdd(ReqDriverAuth driverAuth, Vehicleinfo vehicleinfo) {

		// 添加照片信息封装到集合中
		List<String> listData = this.getListData(driverAuth);
		List<String> listImageName = this.getListName(driverAuth, vehicleinfo);

		// 车牌号
		if (ToolUtil.isNotBlank(driverAuth.getLisencePlate())) {

			vehicleinfo.setLisencePlate(driverAuth.getLisencePlate());
		}
		// 品牌
		if (ToolUtil.isNotBlank(driverAuth.getVehicleType())) {

			vehicleinfo.setVehicleType(driverAuth.getVehicleType());
		}
		// 型号
		if (ToolUtil.isNotBlank(driverAuth.getVehicleModel())) {

			vehicleinfo.setVehicleModel(driverAuth.getVehicleModel());
		}
		// 颜色
		if (ToolUtil.isNotBlank(driverAuth.getVehicleColor())) {

			vehicleinfo.setVehicleColor(driverAuth.getVehicleColor());
		}
		// 提交认证时间
		vehicleinfo.setCreateTime(new Date());
		// 状态 1：审核中
		vehicleinfo.setVstatus(1);
		// 行驶证评语
		vehicleinfo.setXszDescription(null);
		// 驾驶证评语
		vehicleinfo.setJszDescription(null);
		// 车辆图片评语
		vehicleinfo.setVehicleDescription(null);
		// 审核评语
		vehicleinfo.setDescription(null);

		// 执行图片上传
		ImageUpload imageUpload = new ImageUpload();

		if (listData.size() > 0) {

			boolean isSuccess = imageUpload.driverAuthUpload(listData, listImageName);

			// 如果上传成功了
			if (!isSuccess) {
				return null;
			}
		}

		List<String> newImageAddress = this.getNewImageAddress(vehicleinfo);

		return newImageAddress;
	}

	/**
	 * @Title: getNewImageAddress @Description: 获取新的图片地址 @param
	 *         vehicleinfo @author lijinchao @return List<String> @throws
	 */
	private List<String> getNewImageAddress(Vehicleinfo vehicleinfo) {

		List<String> newListImageName = new ArrayList<String>();
		// 行驶证图片地址
		newListImageName.add(ToolUtil.imageAddress(vehicleinfo.getXszImage()));
		// 驾驶证图片地址
		newListImageName.add(ToolUtil.imageAddress(vehicleinfo.getJszImage()));
		// 车辆图片地址
		newListImageName.add(ToolUtil.imageAddress(vehicleinfo.getVehicleImage()));

		return newListImageName;
	}

	/**
	 * @Title: getListName @Description: 根据上传数据命名新的图片 @param driverAuth @param
	 *         vehicleinfo @param @return @author lijinchao @return List
	 *         <String> @throws
	 */
	private List<String> getListName(ReqDriverAuth driverAuth, Vehicleinfo vehicleinfo) {

		List<String> listImageName = new ArrayList<String>();

		// 驾驶证
		String jszImage = ToolUtil.creatImageName();
		// 行驶证
		String xszImage = ToolUtil.creatImageName();
		// 车辆照片
		String vehicleImage = ToolUtil.creatImageName();

		if (vehicleinfo.getIsAuth() == 1) { // 未认证过车主
			listImageName.add(xszImage);
			listImageName.add(jszImage);
			listImageName.add(vehicleImage);
			vehicleinfo.setJszImage(jszImage);
			vehicleinfo.setXszImage(xszImage);
			vehicleinfo.setVehicleImage(vehicleImage);
			// 是否认证过 1：未认证 2：认证过
			vehicleinfo.setIsAuth(2);
		} else {
			// 重新上传行驶证
			if (ToolUtil.isNotBlank(driverAuth.getXszImage())) {

				listImageName.add(xszImage);
				vehicleinfo.setXszImage(xszImage);
			}
			// 重新上传驾驶证
			if (ToolUtil.isNotBlank(driverAuth.getJszImage())) {

				listImageName.add(jszImage);
				vehicleinfo.setJszImage(jszImage);
			}
			// 重新上传车辆图片
			if (ToolUtil.isNotBlank(driverAuth.getVehicleImage())) {

				listImageName.add(vehicleImage);
				vehicleinfo.setVehicleImage(vehicleImage);
			}
		}

		return listImageName;
	}

	/**
	 * @Title: getListData @Description: 获取上传的图片 @param reqDriverAuth @author
	 *         lijinchao @return List<String> @throws
	 */
	private List<String> getListData(ReqDriverAuth reqDriverAuth) {
		// 添加照片信息封装到集合中
		List<String> listData = new ArrayList<String>();

		// 行驶证
		if (ToolUtil.isNotBlank(reqDriverAuth.getXszImage())) {

			listData.add(reqDriverAuth.getXszImage());
		}
		// 驾驶证
		if (ToolUtil.isNotBlank(reqDriverAuth.getJszImage())) {

			listData.add(reqDriverAuth.getJszImage());
		}
		// 车辆图片
		if (ToolUtil.isNotBlank(reqDriverAuth.getVehicleImage())) {

			listData.add(reqDriverAuth.getVehicleImage());
		}

		return listData;
	}

	/**
	 * 
	 * @Title: isProperTiesNull @Description:判断认证车主数据bean是否存在空的数据 @param
	 *         driverAuth 车主认证请求bean @author cheshaowei @return true 参数正确 false
	 *         参数不正确 @throws
	 */
	public boolean isPropertiesTrue(ReqDriverAuth driverAuth) {

		// 不存在该请求bean或者认证人id
		if (driverAuth == null || ToolUtil.isBlank(driverAuth.getDriverId())) {
			return false;
		}

		// 车牌号
		String lisencePlate = driverAuth.getLisencePlate();
		// 车辆品牌
		String vehicleType = driverAuth.getVehicleType();
		// 车辆型号
		String vehicleModel = driverAuth.getVehicleModel();
		// 车辆颜色
		String vehicleColor = driverAuth.getVehicleColor();
		// 行驶证
		String xszImage = driverAuth.getXszImage();
		// 驾驶证图片
		String jszImage = driverAuth.getJszImage();
		// 车辆照片
		String vehicleImage = driverAuth.getVehicleImage();

		if (ToolUtil.isBlank(lisencePlate) && ToolUtil.isBlank(vehicleType) && ToolUtil.isBlank(vehicleModel)
				&& ToolUtil.isBlank(vehicleColor) && ToolUtil.isBlank(xszImage) && ToolUtil.isBlank(jszImage)
				&& ToolUtil.isBlank(vehicleImage)) {
			return false;
		}

		return true;

	}

	@Override
	public void setStatus(DataResponse dataResponse, int status) {

		String message = null;
		switch (status) {
		case SystemCode.SUCCESS:// 成功
			message = SystemCode.SUCCESS_MESSAGE;
			break;
		case SystemCode.ERROR: // 系统异常
			message = SystemCode.ERROR_MESSAGE;
			break;
		case SystemCode.DATA_NULL_ERROR: // 请求数据为空
			message = SystemCode.DATA_NULL_MESSAGE;
			break;
		case SystemCode.LISENCEPLATE_EXITS_ERROR: // 车牌号已被注册
			message = SystemCode.LISENCEPLATE_EXITS_ERROR_MESSAGE;
			break;
		case SystemCode.UPLOAD_ERROR: // 图片上传出现异常
			message = SystemCode.UPLOAD_ERROR_MESSAGE;
		default:
			message = SystemCode.ERROR_MESSAGE;
			break;
		}

		dataResponse.setResponseCode(status);
		dataResponse.setResponseMessage(message);

	}

	/**
	 * 重新进行车主认证
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void reDriverAuth(ReqReDriverAuth reqReDriverAuth, DataResponse dataResponse) {

		// 请求数据为空
		if (reqReDriverAuth == null || reqReDriverAuth.getDriverId() == null) {

			setStatus(dataResponse, SystemCode.DATA_NULL_ERROR);
			return;
		}
		// 创建查询条件
		Criterion criterion = Restrictions.eq("loginId", reqReDriverAuth.getDriverId());
		// 查询车辆信息
		Vehicleinfo vehicleinfo = null;

		try {
			vehicleinfo = super.vehicleinfoDao.queryCriteriaUnResult(criterion, false);
		} catch (Exception e) {
			log.error("重新认证时，查询用户车辆信息出现异常 类：" + this.getClass() + " 方法：reDriverAuth()", e);
			setStatus(dataResponse, SystemCode.ERROR);
			return;
		}

		if (vehicleinfo != null) {
			// 保存该用户提交的旧资料
			boolean isSuccess = super.vehicleAuditService.saveAncientRecord(vehicleinfo);

			if (isSuccess) {

				// 修改当前待审核车主状态(重新认证状态)
				vehicleinfo.setVstatus(4);

				// 重新认证状态
				ResReDriverAuth resReDriverAuth = new ResReDriverAuth(4);
				setStatus(dataResponse, SystemCode.SUCCESS);
				dataResponse.setResponseBody(resReDriverAuth);
				return;
			}
		}

		setStatus(dataResponse, SystemCode.ERROR);
		return;
	}

	/**
	 * @Title: getAllVehicleInfo @Description: 获取全部审核车主信息(数据迁移专用) @author
	 *         yhq @return void @throws
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Vehicleinfo> getAllVehicleInfo() {

		return super.vehicleinfoDao.queryAll(false);
	}

	/**
	 * @Title: deleteAllVehicleInfo @Description: 删除全部审核车主信息(数据迁移专用) @author
	 *         yhq @return void @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean deleteAllVehicleInfo() {

		// 删除全部审核车主信息，并返回值
		int row = 0;
		try {
			row = super.vehicleinfoDao.updateSqlRow("DELETE FROM vehicleinfo");
		} catch (Exception e) {
			log.info("删除全部审核车主信息时出现异常   类：" + this.getClass() + " deleteAllVehicleInfo()", e);
			return false;
		}

		// 判断删除订单是否成功
		if (row > 0) {
			return true;
		}

		return false;
	}

	/**
	 * @Title: updateAllVehicleInfo @Description: 修改全部审核车主的Id(数据迁移专用) @author
	 *         yhq @return void @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean updateAllVehicleInfo(List<Vehicleinfo> vehicleinfos) {

		// 判断传入的审核车主信息是否为空
		if (vehicleinfos != null && vehicleinfos.size() > 0) {
			int number = 1;
			for (Vehicleinfo vehicleinfo : vehicleinfos) {

				// 产生一个订单Id
				String oid = ToolUtil.getUid();

				vehicleinfo.setUvId(oid);

				try {
					super.vehicleinfoDao.save(vehicleinfo);
					Thread.sleep(1);
				} catch (Exception e) {
					log.info("修改审核车主信息Id是出现异常   类：" + this.getClass() + " updateAllVehicleInfo()", e);
					return false;
				}
				number++;
			}

			return true;

		}

		return false;
	}

	/**
	 * @Title: addVehicleInfoByUserLogin @Description:
	 *         根据用户登录信息，创建初始化审核车主信息(数据迁移专用) @author yhq @return void @throws
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean addVehicleInfoByUserLogin(List<UserLogin> userLogins, List<Vehicleinfo> vehicleinfos) {

		int num = 1;

		boolean flag = false;

		if (userLogins.size() > 0) {

			for (UserLogin userLogin : userLogins) {

				int number = 0;

				for (Vehicleinfo vehicleinfo : vehicleinfos) {
					if (userLogin.getUid().equals(vehicleinfo.getLoginId())) {
						number++;
					}
				}

				if (number == 0) {

					Vehicleinfo vehicle = new Vehicleinfo();
					// viid
					vehicle.setUvId(ToolUtil.getUid());
					// loginId
					vehicle.setLoginId(userLogin.getUid());
					// 认证时间
					vehicle.setCreateTime(new Date());
					// 认证状态 0:保留
					vehicle.setVstatus(0);
					// 是否认证
					vehicle.setIsAuth(1);

					try {
						vehicleinfoDao.save(vehicle);
						Thread.sleep(1);
					} catch (Exception e) {
						log.info("添加车主信息时出现异常  类：" + this.getClass() + " addVehicleInfoByUserLogin()", e);
						flag = true;
						return false;
					}
					num++;
				}

			}

			if (flag) {

				return false;
			} else {
				return true;
			}

		}

		return false;
	}

}
